/**
 * @Title:  GroupPhotoActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-4-26 下午5:13:20 
 * @version:  V1.0 
 */

package artid.com.arttogoa.keeponrecord;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import artid.com.arttogoa.BaseActivity;
import artid.com.arttogoa.HomeActivity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.glide.GlideUtil;
import artid.com.arttogoa.parser.ArtworkImageUpload;
import artid.com.arttogoa.parser.ClasslistParse;
import artid.com.arttogoa.parser.FilesBean;
import artid.com.arttogoa.parser.ClasslistParse.Classlist;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AlumAlert;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.TimePickerPopupWindow;
import artid.com.arttogoa.util.TimePickerPopupWindow.onTimeSelectListener;
import artid.com.arttogoa.util.VioceUtils;
import artid.com.arttogoa.view.WheelView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author 熊彬
 * @data: 2016-4-26 下午5:13:20
 * @version: V1.0
 */
public class UploadCompleteGraphActivity extends BaseActivity implements
		OnClickListener, onTimeSelectListener {
	private Button complete;
	private TextView title;
	private String[] timeData = new String[8];
	private TimePickerPopupWindow pickerPopupWindow;
	private AlertDialog alertDialog;
	private WheelView wheelView;
	private ImageView InscribeImage, CompleteImage, vioce;
	private LinearLayout CompimageBtn;
	private TextView type;// 类别
	private EditText imageTitle;// 艺术品名称
	private EditText realname;// 作者zz
	private TextView age;// 年代
	private EditText info;
	private EditText width, height;// 尺寸
	private boolean imageBo;// 是否是完整图
	private static RequestQueue mSingleQueue;
	private static String TAG = "test";
	private String userPhone;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@SuppressLint("CutPasteId")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_complete_graph);
		setContent(UploadCompleteGraphActivity.this, getIntent());
		ArtWorkApp.getInstance().addArtActivity(
				UploadCompleteGraphActivity.this);
		mSingleQueue = Volley.newRequestQueue(this);
		// mSingleQueue = Volley.newRequestQueue(this, new MultiPartStack());
		complete = (Button) findViewById(R.id.btn_complete);
		type = (TextView) findViewById(R.id.tv_option);
		imageTitle = (EditText) findViewById(R.id.et_title);
		realname = (EditText) findViewById(R.id.et_realname);
		age = (TextView) findViewById(R.id.et_age);
		age.setOnClickListener(this);
		info = (EditText) findViewById(R.id.et_info);
		width = (EditText) findViewById(R.id.et_width);
		height = (EditText) findViewById(R.id.et_height);
		width.setInputType(InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_DECIMAL);
		height.setInputType(InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_DECIMAL);
		setPricePoint(width);
		setPricePoint(height);
		InscribeImage = (ImageView) findViewById(R.id.iv_Inscribe_image);
		CompleteImage = (ImageView) findViewById(R.id.iv_complete_image);
		CompimageBtn = (LinearLayout) findViewById(R.id.ll_plus);
		complete.setOnClickListener(this);
		mBack.setOnClickListener(this);
		// type.setOnClickListener(this);
		InscribeImage.setOnClickListener(this);
		CompleteImage.setOnClickListener(this);
		CompimageBtn.setOnClickListener(this);
		title = (TextView) findViewById(R.id.title_text);
		/** 初始化标题标志 **/
		title.setText("上传完整图");
		String Type = MySharedPreferences.getMySharedPreferences(
				UploadCompleteGraphActivity.this).getValue(Cache.ART_TYPE, "");
		Drawable drawable = null;
		if (Type.equals(ArtRecordActivity._PHONE)) {
			drawable = getResources().getDrawable(R.drawable.a_ico_iphone);
			complete.setText("完成并选取局部特征图");
		} else if (Type.equals(ArtRecordActivity._FILING)) {
			drawable = getResources().getDrawable(R.drawable.a_ico_shebei);
			complete.setText("完成并选取微观图");
		}
		// / 这一步必须要做,否则不会显示.
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		title.setCompoundDrawablePadding(20);
		title.setCompoundDrawables(drawable, null, null, null);

		type.setText("书画类");
		age.setText(data[0]);
		String real = AppUtil.getUser().getRealname();
		realname.setText(TextUtils.isEmpty(real) ? "艺术家" : real);
		vioce = (ImageView) findViewById(R.id.iv_vioce);
		vu = new VioceUtils(UploadCompleteGraphActivity.this, vioce, info);
		vu.init();
		initScrollBar();
		userPhone = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue("Phone", "");
		initCache();
		registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
				Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
	}

	/**
	 * 监听是否点击了home键将客户端推到后台
	 */
	private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
		String SYSTEM_REASON = "reason";
		String SYSTEM_HOME_KEY = "homekey";
		String SYSTEM_HOME_KEY_LONG = "recentapps";

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
				String reason = intent.getStringExtra(SYSTEM_REASON);
				if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
					// 表示按了home键,程序到了后台
					storageCache();
				} else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
					// 表示长按home键,显示最近使用的程序列表
					storageCache();
				}
			}
		}
	};

	public void setPricePoint(final EditText editText) {
		editText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.toString().contains(".")) {
					if (s.length() - 1 - s.toString().indexOf(".") > 1) {
						s = s.toString().subSequence(0,
								s.toString().indexOf(".") + 2);
						editText.setText(s);
						editText.setSelection(s.length());
					}
				}
				if (s.toString().trim().substring(0).equals(".")) {
					editText.setText("");
					editText.setSelection(0);
				}

				if (s.toString().startsWith("0")
						&& s.toString().trim().length() < 2) {
					editText.setText("");
					editText.setSelection(0);
					return;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}

		});

	}

	private VioceUtils vu;
	private List<Classlist> class_list;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void initScrollBar() {
		// TODO Auto-generated method stub
		ClasslistParse bean = (ClasslistParse) DataKeeper.readSerializable(
				mContext, ClasslistParse.class);
		if (bean != null) {
			class_list = bean.getClass_list();
		} else {
			class_list = new ArrayList<ClasslistParse.Classlist>();
		}
	}

	String[] data = { "当代（1949年以后）", "近代（1840~1949年之间）", "古代（1840年以前）", "不详" };

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.et_age:
			AlumAlert.initAgeAlertDialog(UploadCompleteGraphActivity.this,
					data, typeCall);
			break;
		case R.id.iv_complete_image:
			imageBo = true;
			initImageDialog();
			break;
		case R.id.iv_Inscribe_image:
			imageBo = false;
			initImageDialog();
			break;
		case R.id.btn_complete:
			complete();
			break;
		case R.id.back_btn:
			finish();
			break;
		default:
			break;
		}
	}

	String typeId = "1";
	CallbackSky typeCall = new CallbackSky() {
		@Override
		public void callBack(int index) {
			// TODO Auto-generated method stub
			age.setText(data[index]);
		}

	};
	ArtworkImageUpload artwork;

	void initCache() {
		String cacheBo = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue(Cache.IS_CACHE + userPhone, "false");
		if (Boolean.valueOf(cacheBo)) {
			String cache = MySharedPreferences.getMySharedPreferences(mContext)
					.getValue(Cache.ART_CACHE + userPhone, "");
			try {
				JSONObject ob = new JSONObject(cache);
				String title = ob.optString("title");
				if (!TextUtils.isEmpty(title)) {
					imageTitle.setText(title);
				}
				String age = ob.optString("age");
				if (!TextUtils.isEmpty(age)) {
					UploadCompleteGraphActivity.this.age.setText(age);
				}
				String width = ob.optString("width");
				if (!TextUtils.isEmpty(width)) {
					UploadCompleteGraphActivity.this.width.setText(width);
				}
				String height = ob.optString("height");
				if (!TextUtils.isEmpty(height)) {
					UploadCompleteGraphActivity.this.height.setText(height);
				}
				String detail = ob.optString("detail");
				if (!TextUtils.isEmpty(detail)) {
					UploadCompleteGraphActivity.this.info.setText(detail);
				}
				String imgdata = ob.optString("imgdata");
				if (!TextUtils.isEmpty(imgdata)) {
					imageUrl = imgdata;
					GlideUtil.setImage1(mContext, imgdata,
							R.drawable.yspba_img_mor, R.drawable.yspba_img_mor,
							CompleteImage);
				}
				String inscribeimg = ob.optString("inscribeimg");
				if (!TextUtils.isEmpty(inscribeimg)) {
					insImageUrl = inscribeimg;
					GlideUtil.setImage1(mContext, inscribeimg,
							R.drawable.yspba_img_mor, R.drawable.yspba_img_mor,
							InscribeImage);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	void storageCache() {
		String cache = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue(Cache.ART_CACHE + userPhone, "");
		try {
			JSONObject ob = new JSONObject(cache);
			String titleString = imageTitle.getText().toString();
			String infoString = info.getText().toString();
			String ageString = age.getText().toString();
			String widthString = width.getText().toString();
			String heightString = height.getText().toString();
			if (!TextUtils.isEmpty(titleString)) {
				ob.put("title", titleString);
			}
			if (!TextUtils.isEmpty(ageString)) {
				ob.put("age", ageString);
			}
			if (!TextUtils.isEmpty(widthString)
					&& !TextUtils.isEmpty(heightString)) {
				ob.put("width", widthString);
				ob.put("height", heightString);
			}
			if (!TextUtils.isEmpty(infoString)) {
				ob.put("detail", infoString);
			}
			if (!TextUtils.isEmpty(imageUrl)) {
				ob.put("imgdata", imageUrl);
			}
			if (!TextUtils.isEmpty(insImageUrl)) {
				ob.put("inscribeimg", insImageUrl);
			}
			MySharedPreferences.getMySharedPreferences(mContext).setValue(
					Cache.ART_CACHE + userPhone, ob.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		storageCache();
		super.onDestroy();
	}

	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	//
	// if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	// // do something...
	//
	// return true;
	// }
	// return super.onKeyDown(keyCode, event);
	// }

	/**
	 * 
	 */
	private void complete() {
		// TODO Auto-generated method stub
		String titleString = imageTitle.getText().toString();
		String infoString = info.getText().toString();
		String realnameString = realname.getText().toString();
		String ageString = age.getText().toString();
		String tpyeString = type.getText().toString();
		String widthString = width.getText().toString();
		String heightString = height.getText().toString();
		if (TextUtils.isEmpty(titleString)) {
			Toast.makeText(mContext, "作品名称不能为空~", Toast.LENGTH_SHORT).show();
			return;
		} else if (TextUtils.isEmpty(realnameString)) {
			Toast.makeText(mContext, "作者名不能为空~", Toast.LENGTH_SHORT).show();
			return;
		} else if (TextUtils.isEmpty(ageString)) {
			Toast.makeText(mContext, "年代不能为空~", Toast.LENGTH_SHORT).show();
			return;

		} else if (TextUtils.isEmpty(widthString)
				|| TextUtils.isEmpty(heightString)) {
			Toast.makeText(mContext, "尺寸不能为空~", Toast.LENGTH_SHORT).show();
			return;
		}
		// else if (TextUtils.isEmpty(infoString)) {
		// Toast.makeText(mContext, "描述不能为空~", Toast.LENGTH_SHORT).show();
		// return;
		// }
		else if (TextUtils.isEmpty(tpyeString)) {
			Toast.makeText(mContext, "类别不能为空~", Toast.LENGTH_SHORT).show();
			return;
		} else if (TextUtils.isEmpty(insImageUrl)) {
			Toast.makeText(mContext, "请选择落款图~", Toast.LENGTH_SHORT).show();
			return;
		} else if (TextUtils.isEmpty(imageUrl)) {
			Toast.makeText(mContext, "请选择完整图~", Toast.LENGTH_SHORT).show();
			return;
		}
		artwork = (ArtworkImageUpload) DataKeeper.readSerializable(mContext,
				ArtworkImageUpload.class);
		artwork.setWidth(widthString);
		artwork.setHeight(heightString);
		artwork.setTitle(titleString);
		artwork.setArt_type("1");
		artwork.setRealname(realnameString);
		artwork.setAge(ageString);
		artwork.setDetail(TextUtils.isEmpty(infoString) ? "" : infoString);
		artwork.setImgdata(imageUrl);
		artwork.setInscribeimg(insImageUrl);
		BitmapFactory.Options options = new BitmapFactory.Options();

		/**
		 * 最关键在此，把options.inJustDecodeBounds = true;
		 * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
		 */
		options.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(imageUrl, options); // 此时返回的bitmap为null
		/**
		 * options.outHeight为原始图片的高
		 */
		Log.e("Test", "Bitmap Height == " + options.outHeight);
		Log.e("Test", "Bitmap w == " + options.outWidth);
		artwork.setDataHeight(options.outHeight);
		artwork.setDataWidth(options.outWidth);
		FileInputStream fis;
		try {
			fis = new FileInputStream(imageUrl);
			long lengh1 = fis.available();
			fis = new FileInputStream(insImageUrl);
			long lengh2 = fis.available();
			fis = new FileInputStream(artwork.getGphotodata());
			long lengh3 = fis.available();
			long lengh = lengh1 + lengh2 + lengh3;
			artwork.setLengh(lengh);
			System.out.println("lengh=" + lengh);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DataKeeper.keepSerializable(UploadCompleteGraphActivity.this, artwork);
		storageCache();
		// Toast.makeText(mContext, artwork.toString(),
		// Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(UploadCompleteGraphActivity.this,
				MicroscopicMapSelectKeepActivity.class);
		Bundle b = new Bundle();
		intent.putExtras(b);
		startActivity(intent);
	}

	String name;
	String fileUrl;

	/**
	 * 
	 */
	private void initImageDialog() {
		// TODO Auto-generated method stub
		alertDialog = AlertUtils.initPhotoAlertDialog(
				UploadCompleteGraphActivity.this,
				UploadCompleteGraphActivity.this.getWindowManager()
						.getDefaultDisplay().getWidth(), new OnClickListener() {
					@Override
					public void onClick(View view) {
						// TODO Auto-generated method stub
						switch (view.getId()) {
						case R.id.tv_phone:
							CameraUtils
									.openCameraImage(UploadCompleteGraphActivity.this);
							alertDialog.dismiss();
							break;
						case R.id.tv_choice:
							Intent intent = new Intent(
									UploadCompleteGraphActivity.this,
									HomeActivity.class);
							if (imageBo)
								intent.putExtra("type", Cache.T_COM);
							else
								intent.putExtra("type", Cache.T_GP);
							startActivityForResult(intent, 2);
							alertDialog.dismiss();
							break;
						default:
							break;
						}
					}
				});
	}

	String url;
	String imageUrl;
	String insImageUrl;

	@SuppressWarnings("unused")
	@SuppressLint({ "SdCardPath", "NewApi" })
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		// if (data != null) {
		Bitmap bitmap = null;
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri = CameraUtils.imageUriFromCamera;
			url = BitmapUtil.getRealFilePath(mContext, uri);
		} else if (requestCode == 2 && resultCode == 3) {
			Bundle bundle = data.getExtras();
			FilesBean fb = (FilesBean) bundle.getSerializable("image");
			url = fb.getImgURL();
			// bitmap = getLoacalBitmap(url); // 从本地取图片
			// info.setText("图片名称：" + fb.getName() + "\n图片大小:" +
			// fb.getFileSize());
		} else if (requestCode == 2 && resultCode == 4) {
			Bundle bundle = data.getExtras();
			FilesBean fb = (FilesBean) bundle.getSerializable("image");
			url = fb.getThumbURL();
			// bitmap = getLoacalBitmap(url); // 从本地取图片
			// info.setText("图片名称：" + fb.getName() + "\n图片大小:" +
			// fb.getFileSize());
		}
		// if (bitmap != null) {
		if (url != null) {
			if (imageBo) {
				imageUrl = url;
				System.out.println("imageUrl=" + imageUrl);
				if (bitmap != null) {
					CompleteImage.setImageBitmap(bitmap);
				} else {
					GlideUtil.setImage1(mContext, url,
							R.drawable.yspba_img_mor, R.drawable.yspba_img_mor,
							CompleteImage);
					CompimageBtn.setVisibility(View.GONE);
					// Glide.with(mContext).load(new File(url))
					// .placeholder(R.drawable.yspba_img_mor)
					// .error(R.drawable.yspba_img_mor)
					// .into(CompleteImage);
				}

			} else {
				insImageUrl = url;
				if (bitmap != null) {
					InscribeImage.setImageBitmap(bitmap);
				} else {
					GlideUtil.setImage1(mContext, url,
							R.drawable.yspba_img_mor, R.drawable.yspba_img_mor,
							InscribeImage);
					CompimageBtn.setVisibility(View.GONE);
					// Glide.with(mContext).load(new File(url))
					// .placeholder(R.drawable.yspba_img_mor)
					// .error(R.drawable.yspba_img_mor)
					// .into(InscribeImage);
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.example.artworkarta.util.TimePickerPopupWindow.onTimeSelectListener
	 * #getTimeString(java.lang.String)
	 */
	@Override
	public void getTimeString(String timeString) {
		// TODO Auto-generated method stub

	}

}
